<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="seanborn," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="seaborn上一篇文章我们讲matplotlib这个库，有没有觉得非常强大呢？即便matplotlib非常强大，对用使用者来说，我们还是要注意很多细节 比如：线条颜色、布局、大小等，那么有没有不让我们设置这些跟实际数据无关的内容呢，答案是有的，就是seaborn seaborn底层还是matplotlib，只是对其进行了一层封装，让使用者不用设置那么多参数，seaborn会提供一些模板，基本就能">
<meta name="keywords" content="seanborn">
<meta property="og:type" content="article">
<meta property="og:title" content="数据分析之seaborn">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/09/20/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="seaborn上一篇文章我们讲matplotlib这个库，有没有觉得非常强大呢？即便matplotlib非常强大，对用使用者来说，我们还是要注意很多细节 比如：线条颜色、布局、大小等，那么有没有不让我们设置这些跟实际数据无关的内容呢，答案是有的，就是seaborn seaborn底层还是matplotlib，只是对其进行了一层封装，让使用者不用设置那么多参数，seaborn会提供一些模板，基本就能">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="数据分析之seaborn">
<meta name="twitter:description" content="seaborn上一篇文章我们讲matplotlib这个库，有没有觉得非常强大呢？即便matplotlib非常强大，对用使用者来说，我们还是要注意很多细节 比如：线条颜色、布局、大小等，那么有没有不让我们设置这些跟实际数据无关的内容呢，答案是有的，就是seaborn seaborn底层还是matplotlib，只是对其进行了一层封装，让使用者不用设置那么多参数，seaborn会提供一些模板，基本就能">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/09/20/1.html"/>





  <title>数据分析之seaborn | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/09/20/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">数据分析之seaborn</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-20T00:43:04+00:00">
                2018-09-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/数据分析/" itemprop="url" rel="index">
                    <span itemprop="name">数据分析</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/数据分析/seanborn/" itemprop="url" rel="index">
                    <span itemprop="name">seanborn</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/09/20/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/09/20/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/09/20/1.html" class="leancloud_visitors" data-flag-title="数据分析之seaborn">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="seaborn"><a href="#seaborn" class="headerlink" title="seaborn"></a>seaborn</h1><p>上一篇文章我们讲matplotlib这个库，有没有觉得非常强大呢？即便matplotlib非常强大，对用使用者来说，我们还是要注意很多细节</p>
<p>比如：线条颜色、布局、大小等，那么有没有不让我们设置这些跟实际数据无关的内容呢，答案是有的，就是seaborn</p>
<p>seaborn底层还是matplotlib，只是对其进行了一层封装，让使用者不用设置那么多参数，seaborn会提供一些模板，基本就能够满足工作需要了，让我开始看看吧</p>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>如果还没有安装，使用如下命令安装即可：<code>pip install seaborn</code></p>
<h2 id="基础使用"><a href="#基础使用" class="headerlink" title="基础使用"></a>基础使用</h2><h3 id="画风设置"><a href="#画风设置" class="headerlink" title="画风设置"></a>画风设置</h3><p>seanborn帮我们内置了一些画图的风格，我们只需要选择可选的风格就可以</p>
<ol>
<li>整体风格设置</li>
</ol>
<p>可选风格：</p>
<pre><code>* darkgrid
* whitegrid
* dark
* white
* ticks
</code></pre><p>试验一下吧，这里给出画图数据<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> seaborn <span class="keyword">as</span> sns</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib <span class="keyword">as</span> mpl</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">%matplotlib inline</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sinplot</span><span class="params">(flip=<span class="number">1</span>)</span>:</span></span><br><span class="line">    x = np.linspace(<span class="number">0</span>, <span class="number">14</span>, <span class="number">100</span>)</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">1</span>, <span class="number">7</span>):</span><br><span class="line">        plt.plot(x, np.sin(x + i * <span class="number">0.5</span>) * (<span class="number">7</span> - i) * flip)</span><br><span class="line"></span><br><span class="line">sinplot()   <span class="comment"># 这里看下结果</span></span><br><span class="line"></span><br><span class="line">sns.set()   <span class="comment"># 充值默认风格</span></span><br><span class="line">sinplot()   <span class="comment"># 对比一下是否有不同</span></span><br></pre></td></tr></table></figure></p>
<ol>
<li><p>使用一种风格</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sns.set_style(<span class="string">"whitegrid"</span>)</span><br><span class="line">data = np.random.normal(size=(<span class="number">20</span>, <span class="number">6</span>)) + np.arange(<span class="number">6</span>) / <span class="number">2</span></span><br><span class="line">sns.boxplot(data=data)</span><br></pre></td></tr></table></figure>
</li>
<li><p>风格调整函数despine</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用默认值，去掉上面与右面的轴线</span></span><br><span class="line">sns.despine()   </span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置轴线与图的偏移</span></span><br><span class="line">sns.despine(offset=<span class="number">10</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置是否去掉某个方向的轴线</span></span><br><span class="line">sns.despine(left=<span class="keyword">True</span>, bottom=<span class="keyword">True</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>在有子图的情况下，我们可能要设置不同风格的子图</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> sns.axes_style(<span class="string">"darkgrid"</span>):</span><br><span class="line">    plt.subplot(<span class="number">211</span>)</span><br><span class="line">    sinplot()</span><br><span class="line">plt.subplot(<span class="number">212</span>)</span><br><span class="line">sinplot()</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h3 id="字体、线条大小等的设置"><a href="#字体、线条大小等的设置" class="headerlink" title="字体、线条大小等的设置"></a>字体、线条大小等的设置</h3><ol>
<li>上面的set_style函数用于设置风格，这里我们介绍set_context主要设置尺寸方面的内容</li>
</ol>
<p><strong>可选context</strong></p>
<pre><code>* paper
* talk
* poster
* notebook
</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sns.set_context(<span class="string">"talk"</span>)</span><br><span class="line">sinplot()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们还能设置字体大小</span></span><br><span class="line">sns.set_context(<span class="string">"notebook"</span>, font_scale=<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置线条宽度</span></span><br><span class="line">sns.set_context(<span class="string">"notebook"</span>, rc=&#123;<span class="string">"lines.linewidth"</span>: <span class="number">4.5</span>&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="颜色设置"><a href="#颜色设置" class="headerlink" title="颜色设置"></a>颜色设置</h3><p>颜色在画图中非常重要，比如可以反映数据的重要程度、可以区分不同组等等，那么seaborn想到了，给我们提供了非常丰富的选择</p>
<p>调色板：</p>
<ul>
<li>颜色很重要</li>
<li>color_palette() 能传入任何Maplotlib所支持的颜色</li>
<li>color_palette() 不写参数则默认颜色</li>
<li>set_palette() 设置所有图的颜色</li>
</ul>
<ol>
<li>默认情况下，seanborn给我们提供了默认六种颜色，深色调</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">current_palette = sns.color_palette()</span><br><span class="line">sns.palplot(current_palette)        <span class="comment"># 画图过程如果不设置颜色，默认会用这六个颜色循环</span></span><br></pre></td></tr></table></figure>
<ol>
<li>如果多余6个指标，要用多余6个颜色怎么办呢，这里介绍圆形画板</li>
</ol>
<p>当有六个以上的分类要区分，最简单的方法就是在一个圆形的颜色区间茁均匀间隔的颜色（这样的色调会保持亮度和饱和度不变）<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">sns.palplot(sns.color_palette(<span class="string">"hls"</span>, <span class="number">12</span>))   <span class="comment"># 一行代码即可调出颜色</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如何使用呢</span></span><br><span class="line">data = np.random.normal(size=(<span class="number">20</span>,<span class="number">8</span>)) + np.arange(<span class="number">8</span>) / <span class="number">2</span></span><br><span class="line">sns.boxplot(data=data, palette=sns.color_palette(<span class="string">"hls"</span>, <span class="number">8</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置亮度与饱和度</span></span><br><span class="line">sns.hls_palette(<span class="number">8</span>, l=<span class="number">0.7</span>, s=<span class="number">0.9</span>)</span><br><span class="line">data = np.random.normal(size=(<span class="number">20</span>,<span class="number">8</span>)) + np.arange(<span class="number">8</span>) / <span class="number">2</span></span><br><span class="line">sns.boxplot(data=data, palette=sns.hls_palette(<span class="number">8</span>, l=<span class="number">0.7</span>, s=<span class="number">0.7</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 总结一下这两个的区别</span></span><br><span class="line">sns.color_palette   <span class="comment"># 指定颜色模式与数量，这里可以设置hls、Paired模式 </span></span><br><span class="line"><span class="comment"># Paired用于生成一对一对深浅的数据</span></span><br><span class="line">sns.hls_palette     <span class="comment"># 对hls这种颜色模式的调节</span></span><br></pre></td></tr></table></figure></p>
<ol>
<li>除了上面介绍的palette设置颜色外，还可以用xkcd命令的颜色指定方式</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 需要长记性查询官网，看都可以有什么选择</span></span><br><span class="line">plt.plot([<span class="number">0</span>,<span class="number">1</span>], [<span class="number">0</span>,<span class="number">1</span>], sns.xkcd_rgb[<span class="string">"pale red"</span>], lw=<span class="number">3</span>)</span><br><span class="line">plt.plot([<span class="number">0</span>,<span class="number">1</span>], [<span class="number">0</span>,<span class="number">2</span>], sns.xkcd_rgb[<span class="string">"medium green"</span>], lw=<span class="number">3</span>)</span><br><span class="line">plt.plot([<span class="number">0</span>,<span class="number">1</span>], [<span class="number">0</span>,<span class="number">3</span>], sns.xkcd_rgb[<span class="string">"denim blue"</span>], lw=<span class="number">3</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li><p>上面我们的所有颜色都是离散的，这里我们介绍如何使用连续的颜色，由浅入深的这种</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sns.palplot(sns.color_palette(<span class="string">"Blues"</span>))     <span class="comment"># 后面加上_r则是又深入浅</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>也可以设置色调线性变换</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sns.palplot(sns.color_palette(<span class="string">"cubehelix"</span>, <span class="number">8</span>))</span><br><span class="line"><span class="comment"># 也可以细节调节</span></span><br><span class="line">sns.palplot(sns.cubehelix_palette(<span class="number">8</span>, start=<span class="number">0.5</span>, rot=<span class="number">-0.75</span>))</span><br></pre></td></tr></table></figure>
<ol>
<li><p>指定一个颜色深浅</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">sns.palplot(sns.light_palette(<span class="string">"green"</span>))</span><br><span class="line">sns.palplot(sns.dark_palette(<span class="string">"green"</span>))</span><br><span class="line">sns.palplot(sns.dark_palette(<span class="string">"green"</span>), reverse=<span class="keyword">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 示例</span></span><br><span class="line">x, y = np.random.multivariate_normal([<span class="number">0</span>, <span class="number">0</span>], [[<span class="number">1</span>, <span class="number">-0.5</span>], [<span class="number">-0.5</span>, <span class="number">1</span>]], size=<span class="number">300</span>).T</span><br><span class="line">pal = sns.dark_palette(<span class="string">"green"</span>, as_cmap=<span class="keyword">True</span>)</span><br><span class="line">sns.kdeplot(x, y, cmap=pal)</span><br></pre></td></tr></table></figure>
</li>
<li><p>也可以自己设定颜色值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 了解即可，不用自己调参数</span></span><br><span class="line">sns.palplot(sns.light_palette((<span class="number">210</span>, <span class="number">90</span>, <span class="number">60</span>), input=<span class="string">"husl"</span>))</span><br></pre></td></tr></table></figure>
</li>
</ol>
<h2 id="实践篇"><a href="#实践篇" class="headerlink" title="实践篇"></a>实践篇</h2><h3 id="单变量分析绘图"><a href="#单变量分析绘图" class="headerlink" title="单变量分析绘图"></a>单变量分析绘图</h3><p>我们通过画图来分析单个变量的分布情况</p>
<p><strong>一些初始化导入（与单变量分析无关）</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">%matplotlib inline</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> scipy <span class="keyword">import</span> stats, integrate</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> seaborn <span class="keyword">as</span> sns</span><br><span class="line">sns.set(color_codes=<span class="keyword">True</span>)</span><br><span class="line">np.random.seed(sum(map(ord, <span class="string">"distributions"</span>)))</span><br></pre></td></tr></table></figure>
<ol>
<li>我们使用直方图来分析单变量情况</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">x = np.random.normal(size=<span class="number">100</span>)</span><br><span class="line">sns.distplot(x, kde=<span class="keyword">False</span>)      <span class="comment"># kde 参数可忽略</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们也可以设置bins</span></span><br><span class="line">sns.distplot(x, bins=<span class="number">20</span>, kde=<span class="keyword">False</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们也可以画出一条趋势线</span></span><br><span class="line">sns.distplot(x, bins=<span class="number">20</span>, kde=<span class="keyword">False</span>, fit=stats.gamma)</span><br></pre></td></tr></table></figure>
<h3 id="多变量分析绘图"><a href="#多变量分析绘图" class="headerlink" title="多变量分析绘图"></a>多变量分析绘图</h3><p>单变量我们使用了直方图分析，对于多变量推荐使用散点图来分析</p>
<ol>
<li>使用散点图分析多个指标</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 指定均值与协方差</span></span><br><span class="line">mean, cov = [<span class="number">0</span>, <span class="number">1</span>], [(<span class="number">1</span>, <span class="number">.5</span>), (<span class="number">.5</span>, <span class="number">1</span>)]</span><br><span class="line">data = np.random.multivariate_normal(mean, cov, <span class="number">200</span>)</span><br><span class="line">df = pd.DataFrame(data, columns=[<span class="string">"x"</span>, <span class="string">"y"</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># seaborn提供的这个函数会同时画出两个指标的直方图情况，也会画图一个散点图</span></span><br><span class="line">sns.jointplot(x=<span class="string">"x"</span>, y=<span class="string">"y"</span>, data=df)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 当我们的数据非常多的时候，点比较集中的位置可能变成一片同色的区域不好区分，这里介绍另外一种方式，自己试验一下吧</span></span><br><span class="line">sns.jointplot(x=<span class="string">"x"</span>, y=<span class="string">"y"</span>, data=df, kind=<span class="string">"hex"</span>, color=<span class="string">"k"</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>假设我们有4个指标，我们想要看4个指标两两之间的关系，我们是不是要来个for循环一次遍历呢？</li>
</ol>
<p>不需要，seanborn帮我们提供了好用的函数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用seaborn内置的数据集 iris</span></span><br><span class="line">iris = sns.load_dataset(<span class="string">"iris"</span>)</span><br><span class="line">sns.pairplot(iris)      <span class="comment"># 自己试验一下吧</span></span><br></pre></td></tr></table></figure>
<ol>
<li>关于离散值变量的绘制</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 我们还是拿小费的例子来看</span></span><br><span class="line">tips = sns.load_dataset(<span class="string">"tips"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 其中的day属性是一个离散值，看不同天与总金额的关系</span></span><br><span class="line">sns.stripplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, data=tips)</span><br><span class="line"><span class="comment"># 从结果可以看到，数据密集的地方都变成一条直线了，不方便分析</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 添加jitter属性，让离散值进行左右小幅度偏移，方便查看分布情况</span></span><br><span class="line">sns.stripplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, data=tips, jitter=<span class="keyword">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 还有另外一种图，更直观的表达这种情况，自己试验一下，看看结果吧</span></span><br><span class="line">sns.swarmplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, data=tips)</span><br></pre></td></tr></table></figure>
<ol>
<li>使用hue属性，更方便的看细化指标</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 还是以tips数据集为例，查看day与total_bill的分布情况，我们可以添加hue属性来区分男女用餐情况</span></span><br><span class="line">sns.swarmplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, hue=<span class="string">"sex"</span>, data=tips)</span><br></pre></td></tr></table></figure>
<ol>
<li>使用盒图</li>
</ol>
<p>在上一篇文章中已经介绍了盒图，这里回顾一下：</p>
<pre><code>1. IQR即统计学概念四分位距，第1/4分位与第3/4分位之间的距离
2. N=1.5IQR  如果有一个值x  x &gt; Q3 + N || x &lt; Q1 - N ， 则x为离群点
</code></pre><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 还是以tips为例</span></span><br><span class="line">sns.boxplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, hue=<span class="string">"time"</span>, data=tips)</span><br><span class="line">sns.boxplot(data=tips)  <span class="comment"># 自动寻找可以画的指标</span></span><br><span class="line">sns.boxplot(data=tips, orient=<span class="string">"h"</span>)  <span class="comment"># 改变方向，如果通过x与y指定的话，交换x与y的属性即可</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 小提琴图</span></span><br><span class="line">sns.violinplot(x=<span class="string">"total_bill"</span>, y=<span class="string">"day"</span>, hue=<span class="string">"sex"</span>, data=tips)  <span class="comment"># 我们将x与y交换了一下位置</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们还可以设置split属性，将hue指定的类别分别花在左右两边，自己试验一下吧</span></span><br><span class="line">sns.violinplot(x=<span class="string">"total_bill"</span>, y=<span class="string">"day"</span>, hue=<span class="string">"sex"</span>, data=tips, split=<span class="keyword">True</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>条形图（同时绘制分类属性）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">titanic = sns.load_dataset(<span class="string">"titanic"</span>)</span><br><span class="line">sns.barplot(x=<span class="string">"sex"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"class"</span>, data=titanic)</span><br></pre></td></tr></table></figure>
<ol>
<li>点图（描述变化情况的图）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">titanic = sns.load_dataset(<span class="string">"titanic"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 关注不同性别的变化趋势</span></span><br><span class="line">sns.pointplot(x=<span class="string">"sex"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"class"</span>, data=titanic)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 关注不同船舱等级的变化趋势</span></span><br><span class="line">sns.pointplot(x=<span class="string">"class"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"sex"</span>, data=titanic)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们还可以美化，设置线条样式与marker样式</span></span><br><span class="line">sns.pointplot(x=<span class="string">"class"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"sex"</span>, data=titanic, palette=&#123;<span class="string">"male"</span>: <span class="string">"g"</span>, <span class="string">"female"</span>: <span class="string">"m"</span>&#125;, markers=[<span class="string">"^"</span>, <span class="string">"o"</span>], linestyles=[<span class="string">"-"</span>, <span class="string">"--"</span>])</span><br><span class="line"><span class="comment"># 这里要特别注意，如果hue指定的是class属性，那么palette参数的字典里的key就应该是船舱等级类别，markers与linestyles的字典里元素也应该是对应类别的数量</span></span><br></pre></td></tr></table></figure>
<ol>
<li>组合</li>
</ol>
<p>我们能够将多个类型的图放在一起</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sns.violinplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, data=tips, inner=<span class="keyword">None</span>)</span><br><span class="line">sns.swarmplot(x=<span class="string">"day"</span>, y=<span class="string">"total_bill"</span>, data=tips, color=<span class="string">"w"</span>, alpha=<span class="number">.5</span>)</span><br></pre></td></tr></table></figure>
<h3 id="回归分析绘图"><a href="#回归分析绘图" class="headerlink" title="回归分析绘图"></a>回归分析绘图</h3><p>seaborn帮我们提供了regplot与implot两个函数来画回归图，推荐使用regplot，相对比较简单，如果感兴趣可以自行查看implot</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 我们还是用seanborn内置的数据集tips，这是一个饭店顾客小费的情况</span></span><br><span class="line">tips = sns.load_dataset(<span class="string">"tips"</span>)</span><br><span class="line">tips.head()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 描述总花费与小费的回归情况</span></span><br><span class="line">sns.regplot(x=<span class="string">"total_bill"</span>, y=<span class="string">"tip"</span>, data=tips) <span class="comment"># 使用上还是非常简单的，分别指定对应指标的列名即可</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 描述吃饭人数与小费的回归情况</span></span><br><span class="line">sns.regplot(x=<span class="string">"size"</span>, y=<span class="string">"tip"</span>, data=tips)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 由于size是离散值，不适合做回归分析，这时我们可以添加一些抖动，就是将离散值稍微随机变动一下</span></span><br><span class="line">sns.regplot(x=<span class="string">"size"</span>, y=<span class="string">"tip"</span>, data=tips, x_jitter=<span class="number">.05</span>)</span><br></pre></td></tr></table></figure>
<h2 id="高级篇"><a href="#高级篇" class="headerlink" title="高级篇"></a>高级篇</h2><h3 id="factorplot"><a href="#factorplot" class="headerlink" title="factorplot"></a>factorplot</h3><p>万能画图函数factorplot</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 不指定类别，默认是点图</span></span><br><span class="line">sns.factorplot(x=<span class="string">"class"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"sex"</span>, data=titanic)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 指定type使用直方图</span></span><br><span class="line">sns.factorplot(x=<span class="string">"class"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"sex"</span>, data=titanic, kind=<span class="string">"bar"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 指定col，根据条件绘制多个图</span></span><br><span class="line">sns.factorplot(x=<span class="string">"class"</span>, y=<span class="string">"survived"</span>, hue=<span class="string">"sex"</span>, col=<span class="string">"alone"</span> ,data=titanic, kind=<span class="string">"bar"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># type参数可选值</span></span><br><span class="line">point       点图，默认</span><br><span class="line">bar         柱形图</span><br><span class="line">count       频次</span><br><span class="line">box         箱体</span><br><span class="line">violin      小提琴</span><br><span class="line">strip       散点</span><br><span class="line">swarm       分散点（树）</span><br></pre></td></tr></table></figure>
<h3 id="FacetGrid"><a href="#FacetGrid" class="headerlink" title="FacetGrid"></a>FacetGrid</h3><p>FacetGrid用于根据不同指标画多个图</p>
<ol>
<li><p>基础</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line">tips = sns.load_dataset(<span class="string">"tips"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 根据time指标画图，time总共只有两个值，因此会画出两个图</span></span><br><span class="line">g = sns.FacetGrid(tips, col=<span class="string">"time"</span>)</span><br><span class="line">g.map(plt.hist, <span class="string">"tip"</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>同样可以设置hue</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">g = sns.FacetGrid(tips, col=<span class="string">"sex"</span>, hue=<span class="string">"smoker"</span>)</span><br><span class="line">g.map(plt.scatter, <span class="string">"total_bill"</span>, <span class="string">"tip"</span>, alpha=<span class="number">.7</span>)</span><br><span class="line">g.add_legend()  <span class="comment"># hue指定的指标需要标识出来</span></span><br></pre></td></tr></table></figure>
<ol>
<li>上面的图形，我们按性别画不同的图，那如果出了性别还有加一个是否吸烟，应该如何做呢</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 设置行为smoker指标，列为time指标</span></span><br><span class="line">g = sns.FacetGrid(tips, row=<span class="string">"smoker"</span>, col=<span class="string">"time"</span>, margin_titles=<span class="keyword">True</span>)</span><br><span class="line"><span class="comment"># color指定颜色深浅，fit_reg用于指定是否画回归的线</span></span><br><span class="line">g.map(sns.regplot, <span class="string">"size"</span>, <span class="string">"total_bill"</span>, color=<span class="string">".5"</span>, fit_reg=<span class="keyword">False</span>, x_jitter=<span class="number">.1</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>我们也可以设置图形大小与长宽比</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">g = sns.FacetGrid(tips, col=<span class="string">"day"</span>, size=<span class="number">4</span>, aspect=<span class="number">.5</span>)</span><br><span class="line">g.map(sns.barplot, <span class="string">"sex"</span>, <span class="string">"total_bill"</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>关于多个图的顺序</li>
</ol>
<p>上面的例子我们通过指定col来表明要画的多个图的区分指标，这时的顺序都是默认的，我们也可以通过row_order来调整顺序</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 以tips数据集为例，找出day这个属性可选的值</span></span><br><span class="line">ordered_days = tips.day.value_counts().index</span><br><span class="line">print(ordered_days)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置一个顺序</span></span><br><span class="line"><span class="keyword">from</span> pandas <span class="keyword">import</span> Categorical</span><br><span class="line">ordered_days = Categorical([<span class="string">'Thur'</span>, <span class="string">'Fri'</span>, <span class="string">'Sat'</span>, <span class="string">'Sun'</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 画图</span></span><br><span class="line">g = sns.FacetGrid(tips, row=<span class="string">"day"</span>, row_order=ordered_days, size=<span class="number">1.7</span>, aspect=<span class="number">4</span>)</span><br><span class="line">g.map(sns.boxplot, <span class="string">"total_bill"</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>其他属性设置（颜色、线宽等）</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">pal = dict(Lunch=<span class="string">"seagreen"</span>, Dinner=<span class="string">"gray"</span>)</span><br><span class="line"><span class="comment"># 通过palette设置颜色，还可以通过hue_kws参数设置通用的属性，比如marker   hue_kws=&#123;"marker": ["^", "v"]&#125;</span></span><br><span class="line">g = sns.FacetGrid(tips, hue=<span class="string">"time"</span>, palette=pal, size=<span class="number">5</span>)</span><br><span class="line"><span class="comment"># s设置点的大小，alpha设置透明度，linewidth=0.7，linewidth=0.5，edgecolor设置边缘颜色</span></span><br><span class="line">g.map(plt.scatter, <span class="string">"total_bill"</span>, <span class="string">"tip"</span>, s=<span class="number">50</span>, alpha=<span class="number">.7</span>, linewidth=<span class="number">.5</span>, edgecolor=<span class="string">"white"</span>)</span><br><span class="line">g.add_legend()</span><br></pre></td></tr></table></figure>
<ol>
<li>设置轴与ticks等属性</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">with</span> sns.axes_style(<span class="string">"white"</span>):</span><br><span class="line">    g = sns.FacetGrid(tips, row=<span class="string">"sex"</span>, col=<span class="string">"smoker"</span>, margin_titles=<span class="keyword">True</span>, size=<span class="number">2.5</span>)</span><br><span class="line">g.map(plt.scatter, <span class="string">"total_bill"</span>, <span class="string">"tip"</span>, color=<span class="string">"#334488"</span>, edgecolor=<span class="string">"white"</span>, lw=<span class="number">.5</span>)</span><br><span class="line"><span class="comment"># 设置轴的labels</span></span><br><span class="line">g.set_axis_labels(<span class="string">"Total bill (US Dollars) "</span>, <span class="string">"Tip"</span>)</span><br><span class="line"><span class="comment"># 设置ticks</span></span><br><span class="line">g.set(xticks=[<span class="number">10</span>, <span class="number">30</span>, <span class="number">50</span>], yticks=[<span class="number">2</span>, <span class="number">6</span>, <span class="number">10</span>])</span><br><span class="line"><span class="comment"># 设置子图间的间距</span></span><br><span class="line">g.fig.subplots_adjust(wspace=<span class="number">.02</span>, hspace=<span class="number">.02</span>)</span><br></pre></td></tr></table></figure>
<h3 id="PairGrid（对图）"><a href="#PairGrid（对图）" class="headerlink" title="PairGrid（对图）"></a>PairGrid（对图）</h3><p>与 sns.pairplot 类似</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">iris = sns.load_dataset(<span class="string">"iris"</span>)</span><br><span class="line">g = sns.PairGrid(iris)          <span class="comment"># 我们还可以设置hue参数，与之前介绍的一样，分类画图 hue="species"</span></span><br><span class="line">g.map(plt.scatter)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 分别设置对角线与非对角线画的图类型</span></span><br><span class="line">g.map_diag(plt.hist)            <span class="comment"># 对角线画直方图</span></span><br><span class="line">g.map_offdiag(plt.scatter)      <span class="comment"># 非对角线画散点图</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果不指定要关注的指标，则会将所有可以画的指标全都画出来，我们可以通过 vars变量来设置要关注的指标</span></span><br><span class="line">g = sns.PairGrid(iris, vars=[<span class="string">"sepal_length"</span>, <span class="string">"sepal_width"</span>], hue=<span class="string">"species"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们也可以设置渐变色</span></span><br><span class="line">g = sns.PairGrid(iris, hue=<span class="string">"species"</span>, palette=<span class="string">"GnBu_d"</span>)</span><br></pre></td></tr></table></figure>
<h3 id="热度图"><a href="#热度图" class="headerlink" title="热度图"></a>热度图</h3><p>用于描述值的变化情况，看一下特征与特征间的相关程度</p>
<ol>
<li><p>一个基础的例子</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 随机构造一个3x3的矩阵，用热度图表示</span></span><br><span class="line">uniform_data = np.random.rand(<span class="number">3</span>,<span class="number">3</span>)</span><br><span class="line">heatmap = sns.heatmap(uniform_data)</span><br><span class="line"><span class="comment"># 非常直观可以看到最大最小值的坐标</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们还可以设置一个最大最小值，小于最小值的所有点都是一个颜色，所有大于最大值的点又是另外一个颜色</span></span><br><span class="line">heatmap = sns.heatmap(uniform_data, vmin=<span class="number">0.2</span>, vmax=<span class="number">0.5</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们也可以设置一个中心值，在中心值的两次有比较清晰的区分</span></span><br><span class="line">normal_data = np.random.randn(<span class="number">3</span>,<span class="number">3</span>)</span><br><span class="line">ax = sns.heatmap(normal_data, center=<span class="number">0</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>以seanborn自带的 flights 数据集进行试验</p>
</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">flights_data = sns.load_dataset(<span class="string">"flights"</span>)</span><br><span class="line">flights.head()  <span class="comment"># 看看内容是啥</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们使用pivot转变一下数据集</span></span><br><span class="line">flights = flights_data.pivot(<span class="string">"year"</span>, <span class="string">"month"</span>, <span class="string">"passengers"</span>)</span><br><span class="line">flights.head()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 画热度图</span></span><br><span class="line">sns.heatmap(flights)    <span class="comment"># 可以看到变化情况</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们可以将对应的值也添加进图形里</span></span><br><span class="line">sns.heatmap(flights, annot=<span class="keyword">True</span>, fmt=<span class="string">"d"</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 我们也可以修改样式，修改线条宽度</span></span><br><span class="line">sns.heatmap(flights, linewidths=<span class="number">.5</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 设置调色板</span></span><br><span class="line">sns.heatmap(flights, linewidths=<span class="number">.5</span>, cmap=<span class="string">"YlGnBu"</span>)</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/seanborn/" rel="tag"># seanborn</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/09/18/1.html" rel="next" title="数据分析之matplotlib">
                <i class="fa fa-chevron-left"></i> 数据分析之matplotlib
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/10/05/1.html" rel="prev" title="机器学习之knn">
                机器学习之knn <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#seaborn"><span class="nav-number">1.</span> <span class="nav-text">seaborn</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">1.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础使用"><span class="nav-number">1.2.</span> <span class="nav-text">基础使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#画风设置"><span class="nav-number">1.2.1.</span> <span class="nav-text">画风设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字体、线条大小等的设置"><span class="nav-number">1.2.2.</span> <span class="nav-text">字体、线条大小等的设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#颜色设置"><span class="nav-number">1.2.3.</span> <span class="nav-text">颜色设置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实践篇"><span class="nav-number">1.3.</span> <span class="nav-text">实践篇</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#单变量分析绘图"><span class="nav-number">1.3.1.</span> <span class="nav-text">单变量分析绘图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多变量分析绘图"><span class="nav-number">1.3.2.</span> <span class="nav-text">多变量分析绘图</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#回归分析绘图"><span class="nav-number">1.3.3.</span> <span class="nav-text">回归分析绘图</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#高级篇"><span class="nav-number">1.4.</span> <span class="nav-text">高级篇</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#factorplot"><span class="nav-number">1.4.1.</span> <span class="nav-text">factorplot</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FacetGrid"><span class="nav-number">1.4.2.</span> <span class="nav-text">FacetGrid</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PairGrid（对图）"><span class="nav-number">1.4.3.</span> <span class="nav-text">PairGrid（对图）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#热度图"><span class="nav-number">1.4.4.</span> <span class="nav-text">热度图</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
